package sharedServlets;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLEncoder;
import java.util.logging.Logger;

import com.tecnick.htmlutils.htmlentities.HTMLEntities;

import controller.Controller;
import dataBase.Order;



public class C2DM {
	private static C2DM inst = new C2DM();
	public static C2DM getInst(){
		return inst;
	}
	private C2DM() {
		// TODO Auto-generated constructor stub
	}


	private final static String AUTH = "authentication";

	private static final String UPDATE_CLIENT_AUTH = "Update-Client-Auth";

	public static final String PARAM_REGISTRATION_ID = "registration_id";

	public static final String PARAM_DELAY_WHILE_IDLE = "delay_while_idle";

	public static final String PARAM_COLLAPSE_KEY = "collapse_key";

	private static final String UTF8 = "UTF-8";

	public int sendMessage(String registrationId,String barTitle,String title,String message, Order order){
		try {
			String auth_token = getToken();
			if(auth_token==null)
				return 1;
			Logger.getLogger("changeStatusBusiness").warning("After Token");
			StringBuilder postDataBuilder = new StringBuilder();
			postDataBuilder.append(PARAM_REGISTRATION_ID).append("=")
			.append(registrationId);
			postDataBuilder.append("&").append(PARAM_COLLAPSE_KEY).append("=")
			.append("0");
			postDataBuilder.append("&").append("data.title").append("=")
			.append(URLEncoder.encode(HTMLEntities.unhtmlentities(title), UTF8));
			postDataBuilder.append("&").append("data.barTitle").append("=")
			.append(URLEncoder.encode(HTMLEntities.unhtmlentities(barTitle), UTF8));
			postDataBuilder.append("&").append("data.msg").append("=")
			.append(URLEncoder.encode(HTMLEntities.unhtmlentities(message), UTF8));
			postDataBuilder.append("&").append("data.orderKey").append("=")
			.append(URLEncoder.encode(order.getKey().getId()+"", UTF8));
			postDataBuilder.append("&").append("data.phone").append("=")
			.append(URLEncoder.encode(order.getPhoneNumber().getNumber()+"", UTF8));
	
			byte[] postData = postDataBuilder.toString().getBytes(UTF8);
	
	
			URL url = new URL("https://android.clients.google.com/c2dm/send");
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			conn.setDoOutput(true);
			conn.setUseCaches(false);
			conn.setRequestMethod("POST");
			conn.setRequestProperty("Content-Type",
			"application/x-www-form-urlencoded;charset=UTF-8");
			conn.setRequestProperty("Content-Length",
					Integer.toString(postData.length));
			conn.setRequestProperty("Authorization", "GoogleLogin auth="
					+ auth_token);
	
			OutputStream out = conn.getOutputStream();
			out.write(postData);
			out.close();
	
			int responseCode = conn.getResponseCode();
			return responseCode;
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return 1;
	}
	public String getToken(){
		HttpURLConnection connection = null;
		URL url = null;
		try {
			url = new URL("https://www.google.com/accounts/ClientLogin");
			connection = (HttpURLConnection) url.openConnection();
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		connection.setDoOutput(true);
		connection.setUseCaches(false);
		connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
		StringBuilder sb = new StringBuilder(); 
		
		addEncodedParameter(sb, "accountType", "GOOGLE");
		addEncodedParameter(sb, "Email", "syncateam");
		addEncodedParameter(sb, "Passwd", "syncahorateam");
		addEncodedParameter(sb, "service", "ac2dm");
		addEncodedParameter(sb, "source", "myCompany-demoApp-1.0.0");
		String data = sb.toString();

		DataOutputStream stream;
		try {
			stream = new DataOutputStream(connection.getOutputStream());
			stream.writeBytes(data);
			stream.flush();
			stream.close();
		
			BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); 
			 
			String line;
			String tokenIdentifier = "Auth=";
			String errorIdentifier = "Error=";
			String token = null;
			StringBuilder errors = new StringBuilder();
			while ((line = reader.readLine()) != null) {
			    if (line.startsWith(tokenIdentifier)) {
			        token = line.substring(tokenIdentifier.length());
			    } else if (line.startsWith(errorIdentifier)) {
			        String error = line.substring(errorIdentifier.length());
			        errors.append(error + System.getProperty("line.separator"));
			    }
			}
			reader.close();
			System.out.println("token: "+token);
			return token;

		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}
	private void addEncodedParameter(StringBuilder sb, String name, String value) {
		 
	    if (sb.length() > 0) {
	        sb.append("&");
	    }
	 
	    try {
	        sb.append(URLEncoder.encode(name, "UTF-8"));
	        sb.append("=");
	        sb.append(URLEncoder.encode(value, "UTF-8"));
	    } catch (UnsupportedEncodingException e) {
	    }
	}

	public void register(String userName,String registrationId){
		Controller.getInstance().register(userName,registrationId);
		
	}
	public void unregister(String userName){
		Controller.getInstance().unregister(userName);
		
	}
	
}
